#!/usr/bin/env bash
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :CentOS7.X IP合法性检查
# Platform :RedHatEL7.x Based Platform
# Version  :0.0.2
# Date     :2013-05-26
# Author   :mugoLH
# Contact  :hxsaj@126.com
# Company  :
# depend on:
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
set -e
#  函数列表 Function list
########## ########## ########## ########## ########## ########## #
info_p() { printf "\e[1;32;40m%-12s %-1s\n\e[0m" "${1}" "${2}" >&1; }
tips_p() { printf "\e[1;36;40m%-12s %-1s\n\e[0m" "${1}" "${2}" >&1; }
error_p() { printf "\e[1;35;40m%-12s %-1s\n\e[0m" "${1}" "${2}" >&1; }

#  检查函数
check_ip() {
	if [[ $(echo "${1}" | awk -F "." '{print NF}') -eq 4 ]] && echo "${1}" | grep -wqe "[0-9]\{1,3\}.[0-9]\{1,3\}.[0-9]\{1,3\}.[0-9]\{1,3\}"; then
		IP_PS=($(echo ${1} | awk -F "." '{print$1" "$2" "$3" "$4}'))
		check_i() {
			if [ ${1} -lt ${2} ] || [ ${1} -gt ${3} ]; then
				error_p "[ ERROR   ]: ${HOST_IP} 不合法"
			fi
		}
		#  检查分段，IP首段限制在1-240，其他段限制在0-255
		check_i ${IP_PS[0]} 1 240
		for i in $(seq 1 3); do
			check_i ${IP_PS[${i}]} 0 255
		done
	else
		error_p "[ ERROR   ]: ${HOST_IP} 不合法"
	fi

}

#  程序主体
if [[ $# -eq 0 ]]; then
	read -p "请输入IP地址：" HOST_IP
	check_ip ${HOST_IP}

elif [[ $# -eq 1 ]]; then
	HOST_IP=${1}
	check_ip ${HOST_IP}
fi
# done
